<!--
 * @Autor: dingxiaolin
 * @Date: 2021-08-28 23:49:10
 * @LastEditors: dingxiaolin
 * @LastEditTime: 2021-09-16 17:02:59
-->
<template>
    <div id="container">
        <div id="panel"></div>
    </div>
    <div class="input-card" style="width: auto">
        <div class="input-item">
            <button class="btn" @click="defaultLayer">默认图层</button>
        </div>
        <div class="input-item">
            <button class="btn" @click="haituLayer">海事图层</button>
        </div>
        <div class="input-item">
            <button class="btn" @click="imageLayer">影像图层</button>
        </div>
    </div>
</template>

<script lang='ts'>
import { defineComponent, reactive, toRefs, ref, computed, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from '@/store'
import { message } from 'ant-design-vue'
import gcoord from 'gcoord'
import { findLastKey, throttle } from 'lodash'
import axios from 'axios'
export default defineComponent({
    name: 'merchant',
    components: {},
    props: {},
    emits: [],
    setup(props, ctx) {
        const router = useRouter()
        const store = useStore()
        const map = ref()
        /**信息窗体 */
        const infoWindow = new AMap.InfoWindow({
            isCustom: true
        })
        const key = 'ce6efc528c9890f66eb7b5dce8b78d5b' //天地图的key
        const state = reactive({
            /**天地图底图 */
            xyzTileLayer: new AMap.TileLayer({
                getTileUrl: `http://t{0,1,2,3,4,5,6,7}.tianditu.gov.cn/DataServer?T=vec_w&tk=${key}&x=[x]&y=[y]&l=[z]`,
                zIndex: 1
            }),
            /**天地图文字标注图 */
            wordTileLayer: new AMap.TileLayer({
                getTileUrl: `http://t{0,1,2,3,4,5,6,7}.tianditu.gov.cn/DataServer?T=cva_w&tk=${key}&x=[x]&y=[y]&l=[z]`,
                zIndex: 2
            }),
            /**天地图网路图 */
            roadTileLayer: new AMap.TileLayer({
                getTileUrl: `http://t{0,1,2,3,4,5,6,7}.tianditu.gov.cn/DataServer?T=cia_w&tk=${key}&x=[x]&y=[y]&l=[z]`,
                zIndex: 3
            }),
            /**天地图卫星图 */
            sateTileLayer: new AMap.TileLayer({
                getTileUrl: `http://t{0,1,2,3,4,5,6,7}.tianditu.gov.cn/DataServer?T=img_w&tk=${key}&x=[x]&y=[y]&l=[z]`,
                zIndex: 1
            }),
            /**纯长江航道图 */
            cjTileUrl: new AMap.TileLayer.WMS({
                url: 'http://geo.jinhx.cn:8089/geoserver/gwc/service/wms',
                tileSize: 256,
                zIndex: 3,
                params: {
                    SERVICE: 'WMS',
                    FORMAT: 'image/png',
                    VERSION: '1.1.1',
                    request: 'GetMap',
                    tiled: true,
                    SRS: 'EPSG:3857',
                    LAYERS: 'marinfo:hq'
                }
            }),
            /**海事图 */
            seaLayer: new AMap.TileLayer({
                getTileUrl: function (x, y, z) {
                    var imgurl = '/ALL/' + z + '/' + x + '/' + y + '.png'
                    return imgurl
                },
                zIndex: 1
            }),
            /**覆盖物群组 */
            overlayGroup: new AMap.OverlayGroup(),
            /**船舶标注 */
            shipMarkers: [] as any
        })
        const options = {
            resizeEnable: true,
            rotateEnable: true,
            pitchEnable: true,
            pitch: 80,
            // rotation: -15,
            viewMode: '2D', //开启3D视图,默认为关闭
            buildingAnimation: false, //楼块出现是否带动画
            // expandZoomRange: true, // 扩展缩放级别到20
            zoom: 14,
            // zooms: [3, 20],
            layers: [state.cjTileUrl, state.xyzTileLayer, state.wordTileLayer], //常规图
            center: [120.586011, 32.013042]
        }
        onMounted(() => {
            //经纬度转换测试
            var result = gcoord.transform(
                [119.502844, 32.204492], // 经纬度坐标
                gcoord.GCJ02, // 当前坐标系
                gcoord.WGS84 // 目标坐标系
            )
            // 创建地图实例
            map.value = new AMap.Map('container', options)
            // 绘制矢量图层
            // drawPolygon()
            // 加载海事资源图层
            otherLayer()
            // 加载控件
            addController()
            // 加载事件
            mapEvent()
            // 加载船舶展示
            showShipMarkers()
        })
        function defaultLayer() {
            var clearGroup = new AMap.LayerGroup([state.sateTileLayer, state.roadTileLayer, state.seaLayer])
            clearGroup.setMap(null)
            var layerGroup = new AMap.LayerGroup([state.cjTileUrl, state.xyzTileLayer, state.wordTileLayer])
            layerGroup.setMap(map.value)
        }
        function haituLayer() {
            var clearGroup = new AMap.LayerGroup([state.cjTileUrl, state.xyzTileLayer, state.wordTileLayer, state.roadTileLayer, state.sateTileLayer])
            clearGroup.setMap(null)
            state.seaLayer.setMap(map.value)
        }
        function imageLayer() {
            var clearGroup = new AMap.LayerGroup([state.cjTileUrl, state.xyzTileLayer, state.wordTileLayer, state.seaLayer])
            clearGroup.setMap(null)
            var layerGroup = new AMap.LayerGroup([state.sateTileLayer, state.roadTileLayer])
            layerGroup.setMap(map.value)
        }
        /**海事资源图层 */
        function otherLayer() {
            //码头
            axios(
                'http://geo.jinhx.cn:8089/geoserver/marinfo/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=marinfo:elec_range_port&maxFeatures=50&outputFormat=application%2Fjson'
            ).then((res) => {
                var geoJSON = res.data
                var area = new AMap.GeoJSON({
                    geoJSON: geoJSON,
                    // 还可以自定义getMarker和getPolyline
                    getPolygon: function (geojson, lnglats) {
                        return new AMap.Polygon({
                            path: lnglats,
                            strokeColor: 'rgba(0,0,0,0.8)',
                            fillColor: 'rgba(0,0,200,0.4)'
                        })
                    }
                })
                map.value.add(area)
                var coordinates = geoJSON.features
                if (coordinates.length > 0) {
                    coordinates.forEach((v) => {
                        let polygonArr = v['geometry']['coordinates'][0]
                        // 创建纯文本标记
                        var text = new AMap.Text({
                            text: v['properties']['range_name'],
                            cursor: 'pointer',
                            position: getCenterPoint(polygonArr),
                            zooms: [14, 18],
                            style: { 'background-color': 'transparent', border: 'none', fontSize: '11px', fontWeight: 'bold' }
                        })
                        text.setMap(map.value)
                    })
                }
            })
            //断面
            axios(
                'http://geo.jinhx.cn:8089/geoserver/marinfo/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=marinfo:elec_range_duanmian&maxFeatures=50&outputFormat=application%2Fjson'
            ).then((res) => {
                var geoJSON = res.data
                var area = new AMap.GeoJSON({
                    geoJSON: geoJSON,
                    // 还可以自定义getMarker和getPolyline
                    getPolygon: function (geojson, lnglats) {
                        return new AMap.Polygon({
                            path: lnglats,
                            strokeWeight: 1,
                            strokeColor: 'rgba(0,0,0,0.8)',
                            fillColor: 'rgba(0,255,255,0)'
                        })
                    }
                })
                // map.value.add(area)
            })
            //电子围栏
            axios(
                'http://geo.jinhx.cn:8089/geoserver/marinfo/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=marinfo:elec_range_enclosure&maxFeatures=50&outputFormat=application%2Fjson'
            ).then((res) => {
                var geoJSON = res.data
                var area = new AMap.GeoJSON({
                    geoJSON: geoJSON,
                    // 还可以自定义getMarker和getPolyline
                    getPolygon: function (geojson, lnglats) {
                        return new AMap.Polygon({
                            path: lnglats,
                            strokeWeight: 2,
                            strokeColor: 'rgba(0,0,0,0.8)',
                            fillColor: 'rgba(153,255,255,0.6)'
                        })
                    }
                })
                map.value.add(area)
                var coordinates = geoJSON.features
                if (coordinates.length > 0) {
                    coordinates.forEach((v) => {
                        let polygonArr = v['geometry']['coordinates'][0]
                        // 创建纯文本标记
                        var text = new AMap.Text({
                            text: v['properties']['range_name'],
                            cursor: 'pointer',
                            position: getCenterPoint(polygonArr),
                            zooms: [14, 18],
                            style: { 'background-color': 'transparent', border: 'none', fontSize: '11px', fontWeight: 'bold' }
                        })
                        text.setMap(map.value)
                    })
                }
            })
        }
        /**船舶定位展示 */
        async function showShipMarkers() {
            // 船舶点位
            // console.log('bbox', map.value.getBounds())
            var layer = new AMap.LabelsLayer({
                zooms: [3, 20],
                zIndex: 1000
                // collision: false,
                // 设置 allowCollision：true，可以让标注避让用户的标注
            })

            const {
                data: { features }
            } = await axios(
                'http://geo.jinhx.cn:8089/geoserver/marinfo/wfs?service=WFS&version=1.0.0&request=GetFeature&typename=marinfo:view_ship_blend&outputFormat=application/json&srsname=EPSG:4326' +
                    '&t=' +
                    new Date().getTime()
            )
            // 设置一个图标对象
            var icon = {
                // 图标类型，现阶段只支持 image 类型
                type: 'image',
                // 图片 url
                image: '',
                // 图片尺寸
                size: [20, 30],
                // 图片相对 position 的锚点，默认为 bottom-center
                anchor: 'center',
                rotation: 50
            }
            features.length > 0 &&
                features.forEach((v) => {
                    const { properties } = v
                    var marker = new AMap.LabelMarker({
                        position: [properties['lng'], properties['lat']],
                        icon,
                        zooms: [5, 18]
                        // extData: {
                        //     guid: properties['guid'],
                        //     content: `<div style="background: rgba(0, 0, 0, 0.3);color:#fff;padding:10px;font-size:12px;"><div>船名：${
                        //         properties['cn_name'] ? properties['cn_name'] : ''
                        //     }</div><div>MMSI：${properties['ship_id']}</div>
                        //      <div>当前速度：${parseFloat(properties['speed']).toFixed(2)}km/h</div><div>更新时间：${properties['recive_time']
                        //         .substring(0, 19)
                        //         .replace(/T/, ' ')}</div></div>`
                        // }
                    })
                    state.shipMarkers.push(marker)
                })
            layer.add(state.shipMarkers)
            map.value.add(layer)
            // features.length > 0 &&
            //     features.forEach((v) => {
            //         const { properties } = v
            //         var marker = new AMap.Marker({
            //             position: [properties['lng'], properties['lat']],
            //             icon: '',
            //             zooms: [5, 18],
            //             autoRotation: false,
            //             extData: {
            //                 guid: properties['guid'],
            //                 content: `<div style="background: rgba(0, 0, 0, 0.3);color:#fff;padding:10px;font-size:12px;"><div>船名：${
            //                     properties['cn_name'] ? properties['cn_name'] : ''
            //                 }</div><div>MMSI：${properties['ship_id']}</div>
            //                  <div>当前速度：${parseFloat(properties['speed']).toFixed(2)}km/h</div><div>更新时间：${properties['recive_time']
            //                     .substring(0, 19)
            //                     .replace(/T/, ' ')}</div></div>`
            //             }
            //         })
            //         // 设置船角度
            //         marker.setAngle(properties['turn_rate'])
            //         // 设置鼠标划过点标记显示的文字提示
            //         const content = `${properties['cn_name'] ? properties['cn_name'] : properties['ship_id']}`
            //         marker.setLabel({
            //             content: content, //设置文本标注内容
            //             direction: 'bottom' //设置文本标注方位
            //         })
            //         //悬入事件
            //         marker.on('mouseover', showInfoOver)
            //         // 数据过期过滤
            //         state.shipMarkers.push(marker)
            //     })
            // map.value.add(state.shipMarkers)
            // await setTimeout(() => {
            //     // await setInterval(() => {
            //     var i = 0
            //     axios(
            //         'http://geo.jinhx.cn:8089/geoserver/marinfo/wfs?service=WFS&version=1.0.0&request=GetFeature&typename=marinfo:view_ship_blend&outputFormat=application/json&srsname=EPSG:4326' +
            //             '&t=' +
            //             new Date().getTime() +
            //             '&bbox=120.50828279689667,31.99278470796343,120.64011873439667,32.023855417191946&t=1631005406199'
            //     ).then((res) => {
            //         console.log('2', res.data.features.length)
            //         res.data.features.forEach((v) => {
            //             const { properties } = v
            //             state.shipMarkers.forEach((marker) => {
            //                 if (properties['guid'] == marker.getExtData().guid) {
            //                     i++
            //                     marker.moveTo([properties['lng'], properties['lat']], properties['speed'])
            //                     // marker.setPosition([properties['lng'], properties['lat']])
            //                     marker.setAngle(properties['turn_rate'])
            //                 }
            //             })
            //         })
            //         console.log('i', i)
            //     })
            // }, 5000)
            /**信息窗体 */
            function showInfoOver(e) {
                const position = e.target.getPosition()
                infoWindow.setContent(e.target.getExtData().content)
                infoWindow.open(map.value, [position['lng'], position['lat']])
            }
            function showInfoOut(e) {
                infoWindow.close()
            }
        }

        /**地图控件 */
        function addController() {
            map.value.plugin(['AMap.Scale', 'AMap.ToolBar', 'AMap.ControlBar'], function () {
                var scale = new AMap.Scale()
                var toolBar = new AMap.ToolBar()
                var controlBar = new AMap.ControlBar()
                map.value.addControl(scale)
                map.value.addControl(toolBar)
                map.value.addControl(controlBar)
            })
        }
        /**地图事件 */
        function mapEvent() {
            //地图加载完成事件
            map.value.on('complete', function () {
                message.success('地图图块加载完毕！当前地图中心点为：' + map.value.getCenter())
            })
            //地图点击事件
            map.value.on('click', showInfoClick)
            function showInfoClick(e) {
                var text = '您在 [ ' + e.lnglat.getLng() + ',' + e.lnglat.getLat() + ' ] 的位置单击了地图！'
                message.success(text)
            }
            //地图缩放事件
            // map.on('zoomstart', mapZoomstart)
            map.value.on('zoomchange', throttle(mapZoom, 300))
            // map.on('zoomend', mapZoomend)
            function mapZoom() {
                var zoom = map.value.getZoom() //获取当前地图级别
                message.success('当前级别:' + zoom)
            }
            // marker.on('click', showInfoM)
            function showInfoM(e) {
                var text = '您在 [ ' + e.lnglat.getLng() + ',' + e.lnglat.getLat() + ' ] 的位置点击了marker！'
                message.success(text)
            }
        }
        function drawPolygon() {
            var polygonArr = new Array() //多边形覆盖物节点坐标数组
            polygonArr.push([119.849207, 32.271868])
            polygonArr.push([119.85091, 32.270464])
            polygonArr.push([119.849389, 32.269609])
            polygonArr.push([119.847693, 32.271229])
            var polygon = new AMap.Polygon({
                path: polygonArr, //设置多边形边界路径
                strokeColor: '#000', //线颜色
                strokeOpacity: 0.4, //线透明度
                strokeWeight: 3, //线宽
                fillColor: '#2C4AD9', //填充色
                fillOpacity: 0.8 //填充透明度
            })
            // 创建纯文本标记
            var text = new AMap.Text({
                text: '扬中码头',
                zooms: [14, 20],
                cursor: 'pointer',
                position: getCenterPoint(polygonArr),
                style: { 'background-color': 'transparent', border: 'none', fontSize: 10 }
            })
            var overlayGroup = new AMap.OverlayGroup([polygon, text])
            map.value.add(overlayGroup)
        }
        /**
         * 获得图形的中心点
         */
        function getCenterPoint(path) {
            var lng = 0.0,
                lat = 0.0
            for (var i = 0; i < path.length; i++) {
                lng = lng + parseFloat(path[i][0])
                lat = lat + parseFloat(path[i][1])
            }
            lng = lng / path.length
            lat = lat / path.length
            return [lng, lat]
        }
        return {
            ...toRefs(state),
            defaultLayer,
            haituLayer,
            imageLayer
        }
    }
})
</script>

<style lang='scss' scoped>
#container {
    height: 100%;
    width: 100%;
}
.input-card {
    bottom: 20rem !important;
}
#panel {
    position: absolute;
    background-color: white;
    max-height: 90%;
    overflow-y: auto;
    top: 10px;
    right: 10px;
    width: 280px;
    z-index: 999;
}
</style>
